#define _DA_SGM5353_C_
/* Includes ---------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "DAC_SGM5353.h"
/* USER CODE END Includes */

/* Types ------------------------------------------------------------*/
/* USER CODE BEGIN Types */

/* USER CODE END Types */

/* Constants --------------------------------------------------------*/
/* USER CODE BEGIN Constants */

/* USER CODE END Constants */

/* Macro ------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
#define DAC_REF_VOLTAGE                                  (2500) // 2500mV = 2.5V

#define DAC_CLK_DELAY                                    (2)

#define DAC_SGM5353_SCK_H()                              (FL_GPIO_SetOutputPin(GPIOD, FL_GPIO_PIN_1))
#define DAC_SGM5353_SCK_L()                              (FL_GPIO_ResetOutputPin(GPIOD, FL_GPIO_PIN_1))

#define DAC_SGM5353_DIN_H()                              (FL_GPIO_SetOutputPin(GPIOD, FL_GPIO_PIN_0))
#define DAC_SGM5353_DIN_L()                              (FL_GPIO_ResetOutputPin(GPIOD, FL_GPIO_PIN_0))

#define DAC_SGM5353_CS_H()                               (FL_GPIO_SetOutputPin(GPIOB, FL_GPIO_PIN_12))
#define DAC_SGM5353_CS_L()                               (FL_GPIO_ResetOutputPin(GPIOB, FL_GPIO_PIN_12))
/* USER CODE END Macro */

/* Variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */

/* USER CODE END Variables */

/* Function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FP */

/* USER CODE END FP */

void vDACSGM5353Init(void)
{
	FL_GPIO_InitTypeDef GPIO_InitStruct;
	
	// SCK:PD1, Output
	// DIN:PD0, Output
    GPIO_InitStruct.pin = FL_GPIO_PIN_0 | FL_GPIO_PIN_1;
    GPIO_InitStruct.mode = FL_GPIO_MODE_OUTPUT;
    GPIO_InitStruct.outputType = FL_GPIO_OUTPUT_PUSHPULL;
    GPIO_InitStruct.pull = FL_DISABLE;
    GPIO_InitStruct.remapPin = FL_DISABLE;
    GPIO_InitStruct.analogSwitch = FL_DISABLE;
    FL_GPIO_Init(GPIOD, &GPIO_InitStruct);

	// CS:PB12, Output
	GPIO_InitStruct.pin = FL_GPIO_PIN_12;
	GPIO_InitStruct.mode = FL_GPIO_MODE_OUTPUT;
    GPIO_InitStruct.outputType = FL_GPIO_OUTPUT_PUSHPULL;
	FL_GPIO_Init(GPIOB, &GPIO_InitStruct);
	
	DAC_SGM5353_CS_L();
}

void vDACSGM5353OutputMV(uint16_t uiMV)
{
	uint16_t uiDAData = 0;
	
	uiDAData = (uint16_t)(((float)uiMV / DAC_REF_VOLTAGE) * 65536.0f);
	
	printf("mv: %04X", uiDAData);
	DAC_SGM5353_CS_L();
	for(uint8_t i = 0; i < 16; i++)
	{
		DAC_SGM5353_SCK_L();

		if(uiDAData & 0x8000)
		{
			DAC_SGM5353_DIN_H();
		}
		else
		{
			DAC_SGM5353_DIN_L();
		}
		vDelay(DAC_CLK_DELAY);
		uiDAData <<= 1;
		
		DAC_SGM5353_SCK_H();
		vDelay(DAC_CLK_DELAY);
	}
	
	DAC_SGM5353_CS_H();
	vDelay(DAC_CLK_DELAY);
	DAC_SGM5353_CS_L();
}
